import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:read_flutter/common/BookUtils.dart';
import 'package:read_flutter/common/Models.dart';
import 'package:read_flutter/common/Tools.dart';
import 'package:read_flutter/pages/read_page.dart';
import 'package:scoped_model/scoped_model.dart';

class BookInfoPage extends StatefulWidget {
  BookInfoPage(this.bookInfo, {Key key}) : super(key: key);
  BookInfo bookInfo;





  @override
  _BookInfoPageState createState() => _BookInfoPageState();
}

class _BookInfoPageState extends State<BookInfoPage> {
  bool isLoading = false;
  List<dynamic> catalogList = [];
  List<BookContent> bookContents = [];
  BookInfo info;
  var _ctl = new ScrollController();
  GlobalKey _listViewKey = new GlobalKey();
  var _itemKeys = {};

  @override
  initState() {
    super.initState();
    info = widget.bookInfo;
  }

  getCatalog() async {
    setState(() {
      isLoading = true;
    });

    Response res = await Tools().request('/search/getcataloglist', {
      'link': widget.bookInfo.cataloglink,
      'source': widget.bookInfo.source
    });
    if (res.data["code"] == "0") {
      catalogList = res.data["result"];
      print(catalogList);

      bookContents =
          await BookTools().updateBookContentList(widget.bookInfo, catalogList);
    }else{
      Tools().showToast("获取目录失败");
    }

    setState(() {
      isLoading = false;
    });
    if (catalogList.length != 0){
      for (BookContent content in bookContents){
        if(widget.bookInfo.lastUrl == content.link){
          jumpTo(content.chapterindex);
        }
      }
    }


  }


  Widget catalogItem(int index) {
    Map<String, dynamic> data = catalogList[index];
    BookContent content = bookContents[index];



    return Container(
      height: 40,
        child:GestureDetector(
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
        child: Text(
          data["CatalogName"].toString(),
          style: TextStyle(color: widget.bookInfo.lastUrl == content.link?Colors.blue:Color(0xff333333), fontSize: 13.0),
        ),
      ),
      onTap: () async {
        Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          return ReadPage(bookContents[index], widget.bookInfo);
        }));
      },
    ));
  }

  @override
  Widget build(BuildContext context) {
    if (catalogList.length == 0) {
      getCatalog();
    }
    return Scaffold(
      appBar: AppBar(
        title: Text('书籍详情'),
      ),
      body: Stack(
        children: <Widget>[
          Container(
            child: Column(
              children: <Widget>[
                Container(
                  width: double.infinity,
                  color: Colors.lightBlue,
                  child: Column(
                    children: <Widget>[
                      Container(
                        child: Image(
                          image: CachedNetworkImageProvider(
                              widget.bookInfo.imagelink),
                          height: 200.0,
                          width: 160.0,
                        ),
                      ),
                      Container(
                        child: Text(
                          widget.bookInfo.showname,
                          style: TextStyle(fontSize: 30.0),
                          softWrap: true,
                        ),
                      ),
                      Container(
                        child: Text(
                          '作者' + widget.bookInfo.author,
                          style: TextStyle(
                              fontSize: 15.0, color: Color(0xff333333)),
                        ),
                      ),
                      Container(
                        height: 50.0,
                        child: Row(
                          children: <Widget>[
                            Expanded(
                                flex: 1,
                                child: GestureDetector(
                                  child: Container(
                                      color: Colors.deepPurple,
                                      height: double.infinity,
                                      child: Center(
                                        child: Text(
                                          info.show ? "移出书架" : "加入书架",
                                          style: TextStyle(
                                              fontSize: 15.0,
                                              color: Colors.white),
                                        ),
                                      )),
                                  onTap: () async {
                                    info.show = !info.show;
                                    BookTools().addBookShelf(info);
                                    final model =
                                        ScopedModel.of<ReadApiModels>(context);
                                    await model.updateBooks();
                                    setState(() {});
                                  },
                                )),
                            Expanded(
                                flex: 1,
                                child: GestureDetector(
                                  child: Container(
                                      height: double.infinity,
                                      color: Colors.green,
                                      child: Center(
                                        child: Text(
                                          widget.bookInfo.lastread != ""
                                              ? "继续阅读"
                                              : "开始阅读",
                                          style: TextStyle(
                                              fontSize: 15.0,
                                              color: Colors.white),
                                        ),
                                      )),
                                  onTap: () async {
                                    if (widget.bookInfo.lastread != "") {
                                      BookContent content =
                                          await bookContentProvider()
                                              .getBookContentWithLink(
                                                  widget.bookInfo.lastUrl);
                                      Navigator.of(context)
                                          .push(MaterialPageRoute(builder: (_) {
                                        return ReadPage(
                                          content,
                                          widget.bookInfo,
                                          con: true,
                                        );
                                      }));
                                    } else {
                                      Navigator.of(context)
                                          .push(MaterialPageRoute(builder: (_) {
                                        return ReadPage(
                                            bookContents[0], widget.bookInfo);
                                      }));
                                    }
                                  },
                                )),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Expanded(
                    child: Container(
                      key: _listViewKey,
                        child: Scrollbar(
                  child: ListView.builder(
                    key: new PageStorageKey("catalog"),
                    controller: _ctl,
                    itemBuilder: (BuildContext context, int index) {
                      return catalogItem(index);
                    },
                    itemCount: catalogList.length,
                  ),
                )))
              ],
            ),
          ),
          loadProgressHUD()
        ],
      ),
    );
  }

  loadProgressHUD() {
    return Offstage(
      offstage: !isLoading,
      child: Container(
          width: double.infinity,
          height: double.infinity,
          color: Color.fromRGBO(0, 0, 0, 0.7),
          child: Center(
              child: Container(
            width: 80.0,
            height: 80.0,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                SpinKitCircle(
                  color: Colors.blue,
                  size: 25.0,
                ),
                Text(
                  "正在处理模型",
                  style: TextStyle(fontSize: 10),
                ),
              ],
            ),
          ))),
    );
  }

  jumpTo(int index){

    double o = 40.0 * index;
    int last = catalogList.length-index;
    if (last * 40<_listViewKey.currentContext.size.height){
      o = 40 * catalogList.length - _listViewKey.currentContext.size.height;
    }
//    _ctl.jumpTo(o);
    _ctl.animateTo(o, duration: Duration(milliseconds: 200), curve: Curves.linear);
  }
}
